<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import {
    adminGetCategoryAPI,
    addCategoryAPI,
    deleteCategoryAPI,
    getDetailCategoryAPI,
    UpdateCategoryAPI
} from '@/apis/admin'
import { useAdminStore } from '@/stores/adminStore'
const adminStore = useAdminStore()
//商品分类数据模型
const categoryList = ref([])
//搜索信息
const level = ref('1')
const parentCategoryId = ref('')
//选择框里面的数据
const selectCategoryList = ref([])
const getSelectCategoryList = async () => {
    try {
        const res = await adminGetCategoryAPI();
        // 筛选 level === 1 的条目
        selectCategoryList.value = res.data.filter(item => item.level === 1);
    } catch (error) {
        console.error('获取分类数据失败:', error);
        selectCategoryList.value = []; // 失败时清空数据
    }
}
onMounted(() => getSelectCategoryList())
//获取分类数据
const getCategoryList = async () => {
    if (level.value === '1') parentCategoryId.value = ''
    //搜索参数
    let searchParams = ref({
        level: level.value,
        parentCategoryId: parentCategoryId.value
    })
    const res = await adminGetCategoryAPI(searchParams.value)
    categoryList.value = res.data
}
onMounted(() => getCategoryList())

//清除搜索信息
const clearSearchInfo = () => {
    level.value = '1'
    parentCategoryId.value = ''
}

//*********************添加分类 *************************/
//控制添加分类弹窗
const dialogVisibleOne = ref(false)
const dialogVisibleTwo = ref(false)

const mainImgUpload = ref()//主图绑定的ref对象

//主副图片上传回调
const mainImgSuccess = (result) => {
    categoryModel.value.categoryImg = result.data
}

//添加分类数据模型
const categoryModel = ref({
    categoryName: '',
    addParentId: '',
    categoryImg: '',
    categoryInfo: ''
})
//添加分类表单校验
const rules = {
    categoryName: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
    ],
    addParentId: [
        { required: true, message: '请选择一级分类', trigger: 'blur' },
    ]
}
const addCategory = async () => {
    try {
        if (!validateForm()) return
        // 提交商品数据
        await addCategoryAPI(categoryModel.value)
        getCategoryList()
        getSelectCategoryList()
        ElMessage.success('分类添加成功')
        dialogVisibleOne.value = false
        dialogVisibleTwo.value = false
        categoryModel.value.categoryName = ''
        categoryModel.value.addParentId = ''
        categoryModel.value.categoryImg = ''
        categoryModel.value.categoryInfo = ''
    } catch (error) {
        ElMessage.error(`操作失败: ${error.message}`)
    }
}
// 表单验证
const validateForm = () => {
    if (!categoryModel.value.categoryName) {
        ElMessage.warning('请输入分类名称')
        return false
    }
    if (!categoryModel.value.categoryImg) {
        ElMessage.warning('请上传主图')
        return false
    }
    return true
}

//*********************修改分类 *************************/
const deleteCategory = async (categoryId) => {
    await deleteCategoryAPI(categoryId)
    ElMessage.success('删除分类成功')
    getCategoryList()
    getSelectCategoryList()
}

const isUpdate = ref(false)
const updateCategoryForm = ref({
    id: '',
    categoryName: '',
    parentId: '',
    parentCategoryName: '',
    categoryImg: '',
    categoryInfo: '',
    level: ''
})
const getDetailCategory = async (categoryId) => {
    const res = await getDetailCategoryAPI(categoryId)
    console.log('得到的res.data');
    console.log(res.data);
    updateCategoryForm.value.id = res.data.id
    updateCategoryForm.value.categoryName = res.data.categoryName
    updateCategoryForm.value.parentId = res.data.parentId
    updateCategoryForm.value.parentCategoryName = res.data.parentCategoryName
    updateCategoryForm.value.categoryImg = res.data.categoryImg
    updateCategoryForm.value.categoryInfo = res.data.categoryInfo
    updateCategoryForm.value.level = res.data.level
    isUpdate.value = true
}
//修改主图片上传回调
const updateCategoryImgSuccess = (result) => {
    updateCategoryForm.value.categoryImg = result.data
}
//开始修改信息
const updateCategory = async () => {
    let postData = ({
        id: updateCategoryForm.value.id,
        categoryName: updateCategoryForm.value.categoryName,
        parentId: updateCategoryForm.value.parentId ,
        parentCategoryName: updateCategoryForm.value.parentCategoryName,
        categoryImg: updateCategoryForm.value.categoryImg,
        categoryInfo: updateCategoryForm.value.categoryInfo ,
        level: updateCategoryForm.value.level
    })
    let res = await UpdateCategoryAPI(postData)
    ElMessage.success(res.message ? res.message : '修改成功')
    getCategoryList()
    getSelectCategoryList()
    isUpdate.value = false;
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>商品分类</span>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisibleOne = true">添加一级分类</el-button>
                    <el-button type="primary" @click="dialogVisibleTwo = true">添加二级分类</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="分类级别：">
                <el-select placeholder="请选择" v-model="level" style="width: 200px;">
                    <el-option label="一级" value="1"></el-option>
                    <el-option label="二级" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="父分类：">
                <el-select placeholder="请选择" v-model="parentCategoryId" style="width: 200px;" :disabled="level === '1'">
                    <template #prefix>
                        <span v-if="level === '1'" style="color: #999; font-size: 16px;">
                            一级分类无需选择父级
                        </span>
                    </template>
                    <el-option v-for="item in selectCategoryList" :key="item.id" :label="item.categoryName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getCategoryList()">搜索</el-button>
                <el-button @click="clearSearchInfo()">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="categoryList" style="width: 100%">
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="分类名称" prop="categoryName"></el-table-column>
            <el-table-column label="父分类">
                <template #default="{ row }">
                    {{ row.parentCategoryName || '无' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="getDetailCategory(row.id)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteCategory(row.id)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisibleOne" title="添加一级分类" width="30%">
            <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <!-- 类图上传 -->
                <el-form-item label="类图" required>
                    <el-upload ref="mainImgUpload" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                        action="/api/upload" name="file"
                        :headers="{ 'Authorization': adminStore.adminInfo.data?.token }" :on-success="mainImgSuccess">
                        <img v-if="categoryModel.categoryImg" :src="categoryModel.categoryImg" class="avatar"
                            width="200" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分类名称" prop="categoryName">
                    <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="内容" :label-width="formLabelWidth" prop="categoryInfo">
                    <el-input v-model="categoryModel.categoryInfo" :autosize="{ minRows: 2, maxRows: 6 }"
                        type="textarea" placeholder="描述一下分类" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisibleOne = false">取消</el-button>
                    <el-button type="primary" @click="addCategory()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 添加二级分类弹窗 -->
        <el-dialog v-model="dialogVisibleTwo" title="添加二级分类" width="40%">
            <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <!-- 类图上传 -->
                <el-form-item label="类图" required>
                    <el-upload ref="mainImgUpload" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                        action="/api/upload" name="file"
                        :headers="{ 'Authorization': adminStore.adminInfo.data?.token }" :on-success="mainImgSuccess">
                        <img v-if="categoryModel.categoryImg" :src="categoryModel.categoryImg" class="avatar"
                            width="200" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="父分类：" required>
                    <el-select placeholder="请选择" v-model="categoryModel.addParentId" style="width: 200px;">
                        <el-option v-for="item in selectCategoryList" :key="item.id" :label="item.categoryName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="categoryName" required>
                    <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="12"></el-input>
                </el-form-item>
                <el-form-item label="内容" :label-width="formLabelWidth" prop="categoryInfo">
                    <el-input v-model="categoryModel.categoryInfo" :autosize="{ minRows: 2, maxRows: 6 }"
                        type="textarea" placeholder="描述一下分类" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisibleTwo = false">取消</el-button>
                    <el-button type="primary" @click="addCategory()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 修改分类弹窗 -->
        <el-dialog v-model="isUpdate" title="修改分类" width="40%">
            <el-form :model="updateCategoryForm" :rules="rules" label-width="100px" style="padding-right: 30px">
                <!-- 类图上传 -->
                <el-form-item label="类图" required>
                    <el-upload ref="mainImgUpload" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                        action="/api/upload" name="file"
                        :headers="{ 'Authorization': adminStore.adminInfo.data?.token }"
                        :on-success="updateCategoryImgSuccess">
                        <img v-if="updateCategoryForm.categoryImg" :src="updateCategoryForm.categoryImg" class="avatar"
                            width="200" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="父分类：" required v-if="updateCategoryForm.parentId !== 0">
                    <el-select placeholder="请选择" v-model="updateCategoryForm.parentId" style="width: 200px;">
                        <el-option v-for="item in selectCategoryList" :key="item.id" :label="item.categoryName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="categoryName" required>
                    <el-input v-model="updateCategoryForm.categoryName" minlength="1" maxlength="12"></el-input>
                </el-form-item>
                <el-form-item label="内容" :label-width="formLabelWidth" prop="categoryInfo">
                    <el-input v-model="updateCategoryForm.categoryInfo" :autosize="{ minRows: 2, maxRows: 6 }"
                        type="textarea" placeholder="描述一下分类" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isUpdate = false">取消</el-button>
                    <el-button type="primary" @click="updateCategory()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>

</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 200px;
            height: 200px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 200px;
            height: 200px;
            text-align: center;
        }
    }
}
</style>